<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\logic;

use app\common\logic\LogicBase;
use \tpfcore\Core;
use think\Validate;

class ProgramConfig extends ApiBase
{
    private $ids;
    public function get_Config()
    {
        $config = config('config.mimi_program');
        if (isset($config['setting']) && $config['setting']) {
            return [0, 'success', $config['setting']];
        } else {
            return [4004, '未获取到配置信息', []];
        }
    }

    public function tpframe_init(){
        $config = config('config.mimi_program');
        if (isset($config['setting']['init']) && $config['setting']['init']) {
            return [0, 'success', $config['setting']['init']];
        } else {
            return [4004, '未获取到配置信息', []];
        }
    }

    public function get_Module()
    {
        $config = config('config.mimi_program');

        if (isset($config['module']) && $config['module']) {

            foreach ($config['module'] as $key => $value) {
                
                $category_id=$value['category_id'];

                $this->ids=[];

                $channel_id = Core::loadModel('Category')->getColumns(['id'=>$category_id],"channel_id");

                $ids = $this->getSonCateGoryIds($category_id,true);

                $order=empty($value['sort'])?"datetime desc":$value['sort'];

                $config['module'][$key]["data"]= $posts_result =Core::loadModel("Posts")->getList(["where"=>["cateid"=>["in",$ids],"ischeck"=>1,"isdelete"=>0],"limit"=>$value['limit'],"order"=>$order,"field"=>"id,title,abstract,updatetime,thumb,source,author,view,likes"]);

                // 如果是视频进行特殊处理
                if(is_array($channel_id) && !empty($channel_id) && $channel_id[0] == 3){

                    foreach ($config['module'][$key]["data"] as $k_v => $v_v) {

                        $result = Core::loadModel("PostsVideos")->getList(["where"=>["posts_id"=>$v_v['id']],"order"=>"datetime desc","limit"=>1]);

                         $config['module'][$key]["data"][$k_v]["data"]=empty($result)?[]:$result[0];

                    }
                }

            }

            return [0, 'success', array_values($config['module'])];
        } else {
            return [4004, '请先配置了模块', []];
        }
    }


    private function getSonCateGoryIds($cateid, $isSelf = false)
    {

        $result = Core::loadModel('Category')->getColumns(['parentid'=>$cateid],"id");

        $isSelf && array_unshift($this->ids, $cateid);
        
        foreach ($result as $key => $value) {
            $this->ids[]=$value;
            $this->getSonCateGoryIds($value);
        }

        return $this->ids;
    }
}